package cn.wit.summit.chwan.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.GameDailyNewAdapter;
import cn.wit.summit.chwan.interfaces.AdapterInterface;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.models.request.DailyNewRequest;
import cn.wit.summit.chwan.models.response.GameDailyNewResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * 每日上新
 * Created by Alan on 2018/4/17.
 */

public class DailyNewActivity extends BaseActivity implements AdapterInterface {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.titleRightTv)
    TextView titleRightTv;
    @Bind(R.id.topTitleLl)
    LinearLayout topTitleLl;

    private int pn = 1;
    private int pc = 20;
    private GameDailyNewAdapter mGameDailyNewAdapter;

    private List<GameDailyNewAdapter.ViewBean> viewBeans = new ArrayList<>();

    private LinearLayoutManager layoutManager;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private int fisrtTitlePo = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_daily_new);
        ButterKnife.bind(this);

        if (retrofitManager == null) {
            retrofitManager = RetrofitManager.getInstance(mContext);
            retrofit = retrofitManager.getRetrofit();
            api = retrofit.create(ApiUtil.class);
        }

        setBarTitleTx(getResources().getString(R.string.recommend_daily_tx));

        initList();
    }

    @Override
    public void reGetData() {
        super.reGetData();
        viewBeans.clear();
        mGameDailyNewAdapter.notifyDataSetChanged();
        pn = 1;
        ketTime = "";
        getDailyNewData();
//        refreshLayout.autoRefresh();
    }

    private void initList() {
        topTitleLl.setVisibility(View.GONE);

        mGameDailyNewAdapter = new GameDailyNewAdapter(this, viewBeans, this);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mGameDailyNewAdapter);
        recyclerView.setFocusable(false);
//        recyclerView.addOnScrollListener(new MyScrollListener());
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
//        refreshLayout.setEnableScrollContentWhenLoaded(false);
//        refreshLayout.setEnableScrollContentWhenRefreshed(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn = 1;
                ketTime = "";
                getDailyNewData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                getDailyNewData();
            }
        });

        showSkeleton();
        pn = 1;
        ketTime = "";
        getDailyNewData();

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (null != layoutManager) {
                    //当前条目索引
                    int position = layoutManager.findFirstVisibleItemPosition();
                    int position2 = layoutManager.findLastVisibleItemPosition();
                    if (fisrtTitlePo==-1) {
                        for (int i=0;i<position2;i++) {
                            int viewType = mGameDailyNewAdapter.getItemViewType(position);
                            if (viewType == GameDailyNewAdapter.ViewType.TYPE_TITLE.ordinal()) {
                                fisrtTitlePo = position;
                                break;
                            }
                        }
                    }
                    if (position > fisrtTitlePo) {
                        topTitleLl.setVisibility(View.VISIBLE);
                    } else {
                        topTitleLl.setVisibility(View.GONE);
                    }

                    int viewType = mGameDailyNewAdapter.getItemViewType(position);
                    if (viewType == GameDailyNewAdapter.ViewType.TYPE_TITLE.ordinal()) {
                        GameDailyNewAdapter.ViewBean viewBean = viewBeans.get(position);
                        GameDailyNewAdapter.ViewBean.TitleBean temp = (GameDailyNewAdapter.ViewBean.TitleBean) viewBean.getObj();
                        titleRightTv.setText(temp.time);
                    }
                }
            }
        });
    }

    private void getDailyNewData() {
        DailyNewRequest tempRequest = retrofitManager.getDailyNewRequest(pn, pc);
        api.getDailyNew(tempRequest).enqueue(new MyCallback<ResponseBase<GameDailyNewResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GameDailyNewResponse> model) {
                hideSkeleton();
                updataUi(model.getData_info());
            }

            @Override
            public void onFailure(int code, String msg) {
                hideSkeleton();
                refreshLayout.finishRefresh(false);
                refreshLayout.finishLoadMore(false);
                refreshLayout.finishRefresh();
                showToast(msg);
            }
        });
    }

    private String ketTime = "";

    private void updataUi(GameDailyNewResponse data) {

        if (data == null) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
            return;
        }

        if (pn == 1) {
            mGameDailyNewAdapter.clearTempData();
            viewBeans.clear();
        }

        if (data.getTop_ad() != null && data.getTop_ad().getJump_ad_switch() == 1 && pn == 1) {
            GameDailyNewAdapter.ViewBean viewBean = new GameDailyNewAdapter.ViewBean(GameDailyNewAdapter.ViewType.TYPE_IMAGE, data.getTop_ad());
            viewBeans.add(viewBean);
        }

        List<GameDailyNewResponse.GameListBean> dataList = data.getGame_list();
        if (dataList == null || dataList.size() == 0) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
            return;
        }

        for (int i = 0; i < dataList.size(); i++) {
            GameDailyNewResponse.GameListBean temp = dataList.get(i);

            if (ketTime.equals("")) {
                ketTime = temp.getGame_f_times();
//                GameDailyNewAdapter.ViewBean lineBean = new GameDailyNewAdapter.ViewBean(GameDailyNewAdapter.ViewType.TYPE_LINE, null);
//                viewBeans.add(lineBean);
                GameDailyNewAdapter.ViewBean.TitleBean titleBean = new GameDailyNewAdapter.ViewBean.TitleBean(temp.getGame_f_times());
                GameDailyNewAdapter.ViewBean viewBean = new GameDailyNewAdapter.ViewBean(GameDailyNewAdapter.ViewType.TYPE_TITLE, titleBean);
                titleRightTv.setText(titleBean.time);
                viewBeans.add(viewBean);
            }

            if (!ketTime.equals(temp.getGame_f_times())) {
                ketTime = temp.getGame_f_times();
                GameDailyNewAdapter.ViewBean lineBean = new GameDailyNewAdapter.ViewBean(GameDailyNewAdapter.ViewType.TYPE_LINE, null);
                viewBeans.add(lineBean);
                GameDailyNewAdapter.ViewBean.TitleBean titleBean = new GameDailyNewAdapter.ViewBean.TitleBean(temp.getGame_f_times());
                GameDailyNewAdapter.ViewBean viewBean = new GameDailyNewAdapter.ViewBean(GameDailyNewAdapter.ViewType.TYPE_TITLE, titleBean);
                viewBeans.add(viewBean);

                GameDailyNewAdapter.ViewBean view = new GameDailyNewAdapter.ViewBean(GameDailyNewAdapter.ViewType.TYPE_LIST, temp);
                viewBeans.add(view);
            } else {
//                GameDailyNewAdapter.ViewBean lineBean = new GameDailyNewAdapter.ViewBean(GameDailyNewAdapter.ViewType.TYPE_LINE_SMALL, null);
//                viewBeans.add(lineBean);

                GameDailyNewAdapter.ViewBean view = new GameDailyNewAdapter.ViewBean(GameDailyNewAdapter.ViewType.TYPE_LIST, temp);
                viewBeans.add(view);
            }
        }

        if (dataList.size() <= 0) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
        } else {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
            pn++;
        }

        mGameDailyNewAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = mGameDailyNewAdapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = mGameDailyNewAdapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));
            ItemListView itemView = view.findViewById(R.id.listItem);
            if (itemView == null) {
                return;
            }
            DownloadViewStroke dowView = itemView.getDownView();
            dowView.updateButn(table);
        }
        super.onEventMainThread(downloadEvent);
    }

    @Override
    public void onAdapterItemClick(View view, int position) {
        switch (view.getId()) {
            case R.id.itemDailyNewIv:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotNetEvent notNetEvent) {
        if (viewBeans != null && viewBeans.size() > 0
                && !notNetEvent.isHasNet) return;
        super.onEventMainThread(notNetEvent);
    }

    @Override
    protected int getSkeletonLayoutId() {
        return R.layout.activity_daily_new_skeleton;
    }
}
